#!/bin/bash
_TYPE="_type_"
_ENTRYPOINT=`cat <<EOF
_entrypoint_
EOF`
_CMD=`cat <<EOF
_cmd_
EOF`

CONTAINER_CMD=""

if [[ $_TYPE == 'ENTRYPOINT' ]];then
    if [ $# -gt 0 ];then
        CONTAINER_CMD="$_ENTRYPOINT $@"
    else
        if [[ $_CMD != '_cmd_' ]];then
            CONTAINER_CMD="$_ENTRYPOINT $_CMD"
        else
            CONTAINER_CMD=$_ENTRYPOINT
        fi
    fi
elif [[ $_TYPE == 'CMD' ]];then
    if [ $# -gt 0 ];then
        CONTAINER_CMD=$@
    else
        CONTAINER_CMD=$_CMD
    fi
fi

# sed -i -e  "s/TENANT_ID/$TENANT_ID/g" -e "s/SERVICE_ID/$SERVICE_ID/g" /etc/confd/templates/env.tmpl
# /opt/bin/confd -node=172.30.42.1:4001 -onetime

wait_pipe=$(mktemp -t "heroku.waitpipe.XXXXXX" -u)
rm -f $wait_pipe
mkfifo $wait_pipe
exec 3<> $wait_pipe

pids=()

trap 'trap - QUIT TERM EXIT; echo "Going down, terminating child processes..." >&2; rm -f ${wait_pipe} || true; echo ${pids[@]}; kill -TERM "${pids[@]}" 2> /dev/null || true; exit' QUIT TERM EXIT

if [[ -t 1 ]]; then
    trap 'trap - INT; kill -INT $$; exit' INT;
else
    trap '' INT;
fi

if [ -z $NO_GRPROXY ]; then
    echo "Starting gr-listener..." >&2
    (
        trap 'echo "gr-listener" >&3;' EXIT
        trap 'kill -TERM $! 2>/dev/null' TERM
        /opt/bin/gr-listener -url=http://region.goodrain.me:8888/v1/conf/$TENANT_ID/$SERVICE_ID -wait_time=60 -frequency=once 2>&1 &
        wait
    ) & pids+=($!)
fi

echo "Starting user process: $CONTAINER_CMD ..." >&2
(
    trap 'echo "$CONTAINER_CMD" >&3;' EXIT
    trap 'kill -TERM $! 2> /dev/null' TERM
    $CONTAINER_CMD 2>&1 &
    wait
) & pids+=($!)

# wait for something to come from the FIFO attached to FD 3, which means that the given process was killed or has failed
# this will be interrupted by a SIGTERM or SIGINT in the traps further up
# if the pipe unblocks and this executes, then we won't read it again, so if the traps further up kill the remaining subshells above, their writing to FD 3 will have no effect
read exitproc <&3
# we'll only reach this if one of the processes above has terminated
echo "Process exited unexpectedly: $exitproc" >&2

# this will trigger the EXIT trap further up and kill all remaining children
exit 1
